package cn.tedu.epidemic.webapi.service.impl;

import cn.tedu.community.commons.excepion.ServiceException;
import cn.tedu.community.commons.pojo.comment.vo.CommentListItemVO;
import cn.tedu.community.commons.pojo.forum.dto.ForumAddNewDTO;
import cn.tedu.community.commons.pojo.forum.dto.ForumUpdateDTO;
import cn.tedu.community.commons.pojo.forum.entity.Forum;
import cn.tedu.community.commons.pojo.forum.entity.ForumCollect;
import cn.tedu.community.commons.pojo.forum.entity.ForumLike;
import cn.tedu.community.commons.pojo.forum.vo.ForumListItemVO;
import cn.tedu.community.commons.pojo.forum.vo.ForumStandardVO;
import cn.tedu.community.commons.restful.JsonPage;
import cn.tedu.community.commons.restful.ServiceCode;
import cn.tedu.epidemic.service.ForumService;
import cn.tedu.epidemic.service.PhotoUploadService;
import cn.tedu.epidemic.webapi.mapper.CommentMapper;
import cn.tedu.epidemic.webapi.mapper.ForumMapper;
import cn.tedu.epidemic.webapi.security.CurrentUser;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

// @DubboService注解,标记的业务逻辑层实现类,其中的所有方法都会注册到Nacos
// 在其他服务启动"订阅"后,就会"发现"当前类中的所有服务,随时可以调用
@DubboService
@Slf4j
@Service
public class ForumServiceImpl implements ForumService {

    @Autowired
    private ForumMapper forumMapper;
    @Autowired
    private CommentMapper commentMapper;
    @Autowired
    private PhotoUploadService uploadService;

    @Override
    public void insert(ForumAddNewDTO addNewDTO) {
        Long userId = CurrentUser.getUserId();
        Forum forum = new Forum();
        BeanUtils.copyProperties(addNewDTO, forum);
        forum.setUserId(userId);
        forum.setAuditStatus(0);
        int insertRows = forumMapper.insert(forum);
        if (insertRows != 1) {
            throw new ServiceException(ServiceCode.ERR_INSERT,
                    "添加论坛失败，请稍后重试！");
        }
    }

    @Override
    public void deleteByIdAndUserId(Long id) {
        Long userId = CurrentUser.getUserId();
        ForumStandardVO standardVO = forumMapper.getStandardById(id);
        if (standardVO == null) {
            String message = "删除论坛失败，论坛不存在！";
            throw new ServiceException(ServiceCode.ERR_NOTFOUND, message);
        }
        if (forumMapper.countByIdAndUserId(id, userId) == 0) {
            throw new ServiceException(ServiceCode.ERR_DELETE, "系统繁忙，您不是该论坛的发布者！");
        }
        int countByIdAndUserId = forumMapper.deleteByIdAndUserId(id, userId);
        String message = "删除论坛失败，请稍后重试！";
        if (countByIdAndUserId != 1) {
            throw new ServiceException(ServiceCode.ERR_DELETE, message);
        }

        if (standardVO.getPhoto()!=null){
            uploadService.deletePhoto(standardVO.getPhoto());
        }

        //删除评论点赞
        Long[] comIds = commentMapper.getComIdsByForumId(id);
        if (comIds.length > 0) {
            commentMapper.deleteLikeByComIds(comIds);
        }

        //根据论坛id删除所有对应的评论（用于用户删除论坛后）
        commentMapper.deleteByForumId(id);
        List<CommentListItemVO> listItemVOS = commentMapper.commentListByForumId(id);
        if (!listItemVOS.isEmpty()) {
            for (CommentListItemVO listItemVO : listItemVOS) {
                if (listItemVO.getPhoto()!=null){
                    uploadService.deletePhoto(listItemVO.getPhoto());
                }
            }
        }
        //删除论坛的收藏
        int countCollectByForumId = forumMapper.countCollectByForumId(id);
        int deleteCollectByForumId = forumMapper.deleteCollectByForumId(id);
        if (deleteCollectByForumId < countCollectByForumId) {
            throw new ServiceException(ServiceCode.ERR_DELETE, message);
        }

        //删除论坛的点赞
        int countLikeByForumId = forumMapper.countLikeByForumId(id);
        int deleteLikeByForumId = forumMapper.deleteLikeByForumId(id);
        if (deleteLikeByForumId < countLikeByForumId) {
            throw new ServiceException(ServiceCode.ERR_DELETE, message);
        }

    }

    @Override
    public void updateInfo(Long forumId, ForumUpdateDTO updateDTO) {
        ForumStandardVO standardById = forumMapper.getStandardById(forumId);
        if (standardById == null) {
            String message = "修改论坛失败，该论坛不存在！";
            throw new ServiceException(ServiceCode.ERR_NOTFOUND, message);
        }
        Long userId = CurrentUser.getUserId();
        Forum forum = new Forum();
        BeanUtils.copyProperties(updateDTO, forum);
        forum.setUserId(userId);
        forum.setAuditStatus(0);
        forum.setId(forumId);
        int update = forumMapper.updateInfo(forum);
        if (update < 1) {
            String message = "修改论坛失败，请稍后重试！";
            throw new ServiceException(ServiceCode.ERR_UPDATE, message);
        }
        if (standardById.getPhoto()!=null && !updateDTO.getPhoto().equals(standardById.getPhoto())){
            uploadService.deletePhoto(standardById.getPhoto());
        }
    }

    @Override
    public void updateAuditStatus(Long id, Integer status) {
        ForumStandardVO standardVO = forumMapper.getStandardById(id);
        if (standardVO == null) {
            String message = "修改审核状态失败，该论坛不存在！";
            throw new ServiceException(ServiceCode.ERR_NOTFOUND, message);
        }
        int updateRows = forumMapper.updateAuditStatus(id, status);
        if (updateRows != 1) {
            String message = "修改审核状态失败，请稍后重试！";
            throw new ServiceException(ServiceCode.ERR_UPDATE, message);
        }
    }

    @Override
    public ForumStandardVO getStandardById(String isLogin, Long id) {
        ForumStandardVO standardVO = forumMapper.getStandardById(id);
        if (standardVO == null) {
            String message = "该论坛不存在！";
            throw new ServiceException(ServiceCode.ERR_NOTFOUND, message);
        }
        Long userId = null;
        if (!isLogin.equals("null")) {
            userId = CurrentUser.getUserId();
        }
        if (forumMapper.countByIdAndUserId(id, userId) > 0) {
            standardVO.setIsCurrentPublish(1);
        }
        return standardVO;
    }

    @Override
    public JsonPage<ForumListItemVO> forumListByPage(Integer page, Integer pageSize) {
        PageHelper.startPage(page, pageSize);
        List<ForumListItemVO> forumListItemVOS = forumMapper.forumList();
        for (ForumListItemVO forumListItemVO : forumListItemVOS) {
            forumListItemVO.setForumCountByLike(forumMapper.countLikeByForumId(forumListItemVO.getId()));
            forumListItemVO.setForumCountByCollect(forumMapper.countCollectByForumId(forumListItemVO.getId()));
        }
        return JsonPage.restPage(new PageInfo<>(forumListItemVOS));
    }

    @Override
    public JsonPage<ForumListItemVO> ListUnaudited(Integer page, Integer pageSize) {
        PageHelper.startPage(page, pageSize);
        List<ForumListItemVO> forumListItemVOS = forumMapper.ListUnaudited();
        if (forumListItemVOS.isEmpty()) {
            String message = "暂无未审核论坛";
            throw new ServiceException(ServiceCode.ERR_SELECT, message);
        }
        return JsonPage.restPage(new PageInfo<>(forumListItemVOS));
    }

    @Override
    public JsonPage<ForumListItemVO> ListAudited(Integer page, Integer pageSize) {
        PageHelper.startPage(page, pageSize);
        List<ForumListItemVO> forumListItemVOS = forumMapper.ListAudited();
        if (forumListItemVOS.isEmpty()) {
            String message = "暂无已审核论坛";
            throw new ServiceException(ServiceCode.ERR_SELECT, message);
        }
        return JsonPage.restPage(new PageInfo<>(forumListItemVOS));
    }

    @Override
    public JsonPage<ForumListItemVO> forumListByUserId(Integer page, Integer pageSize) {
        Long userId = CurrentUser.getUserId();
        PageHelper.startPage(page, pageSize);
        List<ForumListItemVO> forumListItemVOS = forumMapper.forumListByUserId(userId);
        if (forumListItemVOS.isEmpty()) {
            throw new ServiceException(ServiceCode.ERR_SELECT, "您还未发布论坛！");
        }
        for (ForumListItemVO forumListItemVO : forumListItemVOS) {
            forumListItemVO.setForumCountByLike(forumMapper.countLikeByForumId(forumListItemVO.getId()));
            forumListItemVO.setForumCountByCollect(forumMapper.countCollectByForumId(forumListItemVO.getId()));
        }
        return JsonPage.restPage(new PageInfo<>(forumListItemVOS));
    }

    @Override
    public String addCollect(Long forumId) {
        ForumStandardVO standardById = forumMapper.getStandardById(forumId);
        if (standardById == null) {
            String message = "收藏论坛失败，该论坛已不存在！";
            throw new ServiceException(ServiceCode.ERR_NOTFOUND, message);
        }

        if (standardById.getAuditStatus() == 0) {
            throw new ServiceException(ServiceCode.ERR_SELECT,
                    "请等待管理员审核！");
        }
        if (standardById.getAuditStatus() == 2) {
            throw new ServiceException(ServiceCode.ERR_SELECT,
                    "论坛存在敏感信息或图片，请编辑修改后等待管理员审核!");
        }

        Long userId = CurrentUser.getUserId();
        int countByIdUserId = forumMapper.countByIdUserId(forumId, userId);
        if (countByIdUserId >= 1) {
            int deleteCollect = forumMapper.deleteCollect(forumId, userId);
            if (deleteCollect < 1) {
                throw new ServiceException(ServiceCode.ERR_DELETE, "取消收藏论坛失败，请稍后重试！");
            }
            return "取消收藏成功！";
        }
        ForumCollect forumCollect = new ForumCollect();
        forumCollect.setForumId(forumId);
        forumCollect.setUserId(userId);
        int add = forumMapper.addCollect(forumCollect);
        if (add < 1) {
            String message = "收藏论坛失败，请稍后重试！";
            throw new ServiceException(ServiceCode.ERR_INSERT, message);
        }
        return "收藏论坛成功！";
    }

    @Override
    public JsonPage<ForumListItemVO> forumListByCollect(Integer page, Integer pageSize) {
        Long userId = CurrentUser.getUserId();
        PageHelper.startPage(page, pageSize);
        List<ForumListItemVO> collectList = forumMapper.getCollectList(userId);
        log.debug("Service层查询我的收藏论坛：数据是：{}",collectList);
        if (collectList.isEmpty()){
            throw new ServiceException(ServiceCode.ERR_NOTFOUND,"您暂无收藏论坛！");
        }
        for (ForumListItemVO forumListItemVO : collectList) {
            forumListItemVO.setForumCountByLike(forumMapper.countLikeByForumId(forumListItemVO.getId()));
            forumListItemVO.setForumCountByCollect(forumMapper.countCollectByForumId(forumListItemVO.getId()));
        }
        return JsonPage.restPage(new PageInfo<>(collectList));
    }

    @Override
    public String addLike(Long forumId) {
        ForumStandardVO standardById = forumMapper.getStandardById(forumId);
        if (standardById == null) {
            String message = "点赞失败，该论坛已不存在！";
            throw new ServiceException(ServiceCode.ERR_NOTFOUND, message);
        }

        if (standardById.getAuditStatus() == 0) {
            throw new ServiceException(ServiceCode.ERR_SELECT,
                    "请等待管理员审核！");
        }
        if (standardById.getAuditStatus() == 2) {
            throw new ServiceException(ServiceCode.ERR_SELECT,
                    "论坛存在敏感信息或图片，请编辑修改后等待管理员审核!");
        }

        Long userId = CurrentUser.getUserId();
        if (forumMapper.countByForumIdUserId(forumId, userId) >= 1) {
            int deleteLike = forumMapper.deleteLike(forumId, userId);
            if (deleteLike != 1) {
                throw new ServiceException(ServiceCode.ERR_DELETE, "取消点赞失败，请稍后重试！");
            }
            return "取消点赞成功！";
        }

        ForumLike forumLike = new ForumLike();
        forumLike.setForumId(forumId);
        forumLike.setUserId(userId);
        int addLike = forumMapper.addLike(forumLike);
        if (addLike != 1) {
            String message = "点赞论坛失败，请稍后重试！";
            throw new ServiceException(ServiceCode.ERR_INSERT, message);
        }
        return "点赞论坛成功！";
    }
}
